﻿/**************************************************
   * 文 件 名：Common.cs
   * Copyright(c) 2014
   * 创 建 人 ：
   * 创建日期：2014-01-25
   * 修 改 人 ：
   * 修改日期：
   * 备注描述：常用操作工具类
   *************************************************/
using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;

namespace Partner.Utility
{
    /// <summary>
    /// 常用工具类
    /// </summary>
    [Serializable]   
    public static class ComFunc
    {
        /// <summary>
        /// 获取6位随机验证码
        /// </summary>
        /// <returns></returns>
        public static int GetRandom()
        {
            var random = new Random(unchecked((int)(DateTime.Now.Ticks)));
            //睡眠1毫秒，让随机种子不一致   (多线程web应用里未必起效)
            //System.Threading.Thread.Sleep(1);
            return random.Next(100000, 999999);
        }

        ///// <summary>
        ///// 数据类型转换
        ///// </summary>
        ///// <param name="value">要转换类型的对象</param>
        ///// <param name="conversionType">要返回的对象的类型。</param>
        ///// <returns></returns>
        //public static object ChangeType(object value, Type conversionType)
        //{
        //    if (value == DBNull.Value) return null;
        //    if (value.GetType() != conversionType)
        //    {
        //        if (!conversionType.IsGenericType)
        //        {
        //            value = Convert.ChangeType(value, conversionType);
        //        }
        //        else if (conversionType.GetGenericTypeDefinition() == typeof(Nullable<>))
        //        {
        //            value = Convert.ChangeType(value, Nullable.GetUnderlyingType(conversionType));
        //        }
        //        else
        //        {
        //            throw new InvalidCastException(string.Format("从类型 \"{0}\" 转换到类型 \"{1}\" 无效.",
        //                value.GetType().FullName, conversionType.FullName));
        //        }
        //    }
        //    return value;
        //}

        ///// <summary>
        ///// 加载程序集，并释放加载文件
        ///// </summary>
        ///// <param name="filename"></param>
        ///// <returns></returns>
        //public static Assembly LoadDll(string filename)
        //{
        //    var loader = new AssemblyLoader();
        //    try
        //    {
        //        var assembly = loader.LoadAssembly(filename);
        //        loader.Unload(filename);
        //        loader = null;
        //        return assembly;
        //    }
        //    catch (Exception ex)
        //    {

        //    }
        //    return null;
        //}

        ///// <summary>
        ///// 根据自动版本号获取程序集编译时间
        ///// </summary>
        ///// <param name="assembly">程序集</param>
        ///// <returns>程序集编译时间</returns>
        //public static DateTime GetBuildTime(Assembly assembly)
        //{
        //    int revsion = assembly.GetName().Version.Revision;   //获取修订号
        //    int build = assembly.GetName().Version.Build;           //获取内部版本号
        //    var dtbase = new DateTime(2000, 1, 1, 0, 0, 0);          //微软编译基准时间
        //    var tsbase = new TimeSpan(dtbase.Ticks);
        //    var ts = new TimeSpan(tsbase.Days + build, 0, 0, revsion * 2); //编译时间，注意修订号要*2
        //    var dt = new DateTime(ts.Ticks);   //转换成编译时间
        //    return dt;
        //}

        ///// <summary>
        ///// 获取方法调用信息
        ///// </summary>
        ///// <param name="predicate">条件</param>
        ///// <returns></returns>
        //public static CallInfo GetCallInfos(Predicate<CallInfo> predicate = null)
        //{
        //    var match = new Predicate<CallInfo>(ci =>
        //        ci.FileFullName != null &&
        //        ci.Method.IsPublic &&
        //        !ci.ClassName.Contains("<>c__DisplayClass") &&
        //        !ci.Method.DeclaringType.IsAutoClass &&
        //        (predicate == null || predicate(ci))
        //    );
        //    var st = new StackTrace(true);
        //    var fs = st.GetFrames();
        //    CallInfo callinfo = null;
        //    CallInfo lastcallinfo = null;
        //    for (int i = 1; i < fs.Length; i++)
        //    {
        //        lastcallinfo = new CallInfo(fs[i]);
        //        if (match(lastcallinfo))
        //        {
        //            var temp = callinfo;
        //            callinfo = lastcallinfo;
        //            callinfo.Next = temp;
        //            if (callinfo.FileFullName.ToLower().EndsWith(".aspx.cs"))
        //            {
        //                break;
        //            }
        //        }
        //    }
        //    return callinfo;
        //}
        ///// <summary>
        ///// 从动态库的 XML 文件获取摘要信息
        ///// </summary>
        ///// <param name="xmlFileName">XML文件名</param>
        ///// <param name="name">名称</param>
        ///// <returns>摘要信息</returns>
        //public static string GetSummaryByXML(string xmlFileName, string name)
        //{
        //    try
        //    {
        //        EnvDTE.DTE devenv = (EnvDTE.DTE)Marshal.GetActiveObject("VisualStudio.DTE.10.0");
        //        string projectFile = devenv.ActiveDocument.ProjectItem.ContainingProject.FileName;
        //        System.IO.FileInfo info = new System.IO.FileInfo(projectFile);
        //        string xmlfile = Path.Combine(info.Directory.FullName, "Bin", xmlFileName);
        //        XElement doc = XElement.Load(xmlfile);
        //        var result = from xe in doc.Descendants("member")
        //                     where xe.Attribute("name").Value.EndsWith(name)
        //                     select xe.Element("summary").Value;
        //        if (result.Count() > 0)
        //        {
        //            return result.FirstOrDefault();
        //        }
        //        return null;
        //    }
        //    catch (Exception ex)
        //    {
        //        return ex.Message;
        //    }
        //}

        ///<summary>
        /// 返回 GUID 用于数据库操作，特定的时间代码可以提高检索效率
        /// </summary>
        /// <returns>COMB (GUID 与时间混合型) 类型 GUID 数据</returns>
        public static Guid NewCombGuid()
        {
            byte[] guidArray = System.Guid.NewGuid().ToByteArray();
            DateTime baseDate = new DateTime(1900, 1, 1);
            DateTime now = DateTime.Now;
            // Get the days and milliseconds which will be used to build the byte string 
            TimeSpan days = new TimeSpan(now.Ticks - baseDate.Ticks);
            TimeSpan msecs = new TimeSpan(now.Ticks - (new DateTime(now.Year, now.Month, now.Day).Ticks));
            // Convert to a byte array 
            // Note that SQL Server is accurate to 1/300th of a millisecond so we divide by 3.333333 
            byte[] daysArray = BitConverter.GetBytes(days.Days);
            byte[] msecsArray = BitConverter.GetBytes((long)(msecs.TotalMilliseconds / 3.333333));
            // Reverse the bytes to match SQL Servers ordering 
            Array.Reverse(daysArray);
            Array.Reverse(msecsArray);
            // Copy the bytes into the guid 
            Array.Copy(daysArray, daysArray.Length - 2, guidArray, guidArray.Length - 6, 2);
            Array.Copy(msecsArray, msecsArray.Length - 4, guidArray, guidArray.Length - 4, 4);
            return new System.Guid(guidArray);
        }

        /// <summary>
        /// 从 SQL SERVER 返回的 GUID 中生成时间信息
        /// </summary>
        /// <param name="guid">包含时间信息的 COMB </param>
        /// <returns>时间</returns>
        public static DateTime GetDateFromCombGuid(System.Guid combGuid)
        {
            DateTime baseDate = new DateTime(1900, 1, 1);
            byte[] daysArray = new byte[4];
            byte[] msecsArray = new byte[4];
            byte[] guidArray = combGuid.ToByteArray();

            // Copy the date parts of the guid to the respective byte arrays. 
            Array.Copy(guidArray, guidArray.Length - 6, daysArray, 2, 2);
            Array.Copy(guidArray, guidArray.Length - 4, msecsArray, 0, 4);

            // Reverse the arrays to put them into the appropriate order 
            Array.Reverse(daysArray);
            Array.Reverse(msecsArray);

            // Convert the bytes to ints 
            int days = BitConverter.ToInt32(daysArray, 0);
            int msecs = BitConverter.ToInt32(msecsArray, 0);
            DateTime date = baseDate.AddDays(days);
            date = date.AddMilliseconds(msecs * 3.333333);
            return date;
        }

        ///// <summary>
        ///// 把Image转换成byte[]
        ///// </summary>
        ///// <param name="image">image</param>
        ///// <returns>获取到的byte[]</returns>
        //public static byte[] GetBytesFromImage(Image image, out string fileType)
        //{
        //    byte[] bt = null;
        //    fileType = string.Empty;
        //    if (!image.Equals(null))
        //    {
        //        using (MemoryStream mStream = new MemoryStream())
        //        {
        //            if (image.RawFormat.Guid == System.Drawing.Imaging.ImageFormat.Tiff.Guid)
        //            {
        //                image.Save(mStream, System.Drawing.Imaging.ImageFormat.Tiff);
        //                fileType = ".tiff";
        //            }
        //            else if (image.RawFormat.Guid == System.Drawing.Imaging.ImageFormat.Gif.Guid)
        //            {
        //                image.Save(mStream, System.Drawing.Imaging.ImageFormat.Gif);
        //                fileType = ".gif";
        //            }
        //            else if (image.RawFormat.Guid == System.Drawing.Imaging.ImageFormat.Jpeg.Guid)
        //            {
        //                image.Save(mStream, System.Drawing.Imaging.ImageFormat.Jpeg);
        //                fileType = ".jpg";
        //            }
        //            else if (image.RawFormat.Guid == System.Drawing.Imaging.ImageFormat.Bmp.Guid)
        //            {
        //                image.Save(mStream, System.Drawing.Imaging.ImageFormat.Bmp);
        //                fileType = ".bmp";
        //            }
        //            else if (image.RawFormat.Guid == System.Drawing.Imaging.ImageFormat.Png.Guid)
        //            {
        //                image.Save(mStream, System.Drawing.Imaging.ImageFormat.Png);
        //                fileType = ".png";
        //            }
        //            else if (image.RawFormat.Guid == System.Drawing.Imaging.ImageFormat.Icon.Guid)
        //            {
        //                image.Save(mStream, System.Drawing.Imaging.ImageFormat.Icon);
        //                fileType = ".ico";
        //            }
        //            bt = new byte[mStream.Length];
        //            mStream.Position = 0;//设置留的初始位置
        //            mStream.Read(bt, 0, Convert.ToInt32(bt.Length));
        //        }
        //    }
        //    return bt;
        //}

        //public static byte[] GetBytesFromFile(string fileName, out string fileType)
        //{
        //    byte[] bt = null;
        //    fileType = string.Empty;
        //    if (!string.IsNullOrWhiteSpace(fileName))
        //    {
        //        FileInfo fileInfo = new FileInfo(fileName);
        //        fileType = fileInfo.Extension;
        //        FileStream fs = fileInfo.OpenRead();
        //        bt = new byte[fs.Length];
        //        int offset = 0;
        //        int remaining = bt.Length;
        //        while (remaining > 0)
        //        {
        //            int read = fs.Read(bt, offset, remaining);
        //            // 增加偏移量
        //            offset += read;
        //            // 减少剩余的字节数
        //            remaining -= read;
        //        }
        //    }
        //    return bt;
        //}

        ///// <summary>
        ///// 把Image转换成byte[]
        ///// </summary>
        ///// <param name="imageFilename">图片文件地址(本机)</param>
        ///// <param name="fileType">图片类型</param>
        ///// <returns>获取到的byte[]</returns>
        //public static byte[] GetBytesFromImage(string imageFilename, out string fileType)
        //{
        //    byte[] bt = null;
        //    fileType = string.Empty;
        //    if (!string.IsNullOrWhiteSpace(imageFilename))
        //    {
        //        Image image = Image.FromFile(imageFilename);
        //        if (!image.Equals(null))
        //        {
        //            using (MemoryStream mStream = new MemoryStream())
        //            {
        //                if (image.RawFormat.Guid == System.Drawing.Imaging.ImageFormat.Tiff.Guid)
        //                {
        //                    image.Save(mStream, System.Drawing.Imaging.ImageFormat.Tiff);
        //                    fileType = ".tiff";
        //                }
        //                else if (image.RawFormat.Guid == System.Drawing.Imaging.ImageFormat.Gif.Guid)
        //                {
        //                    image.Save(mStream, System.Drawing.Imaging.ImageFormat.Gif);
        //                    fileType = ".gif";
        //                }
        //                else if (image.RawFormat.Guid == System.Drawing.Imaging.ImageFormat.Jpeg.Guid)
        //                {
        //                    image.Save(mStream, System.Drawing.Imaging.ImageFormat.Jpeg);
        //                    fileType = ".jpg";
        //                }
        //                else if (image.RawFormat.Guid == System.Drawing.Imaging.ImageFormat.Bmp.Guid)
        //                {
        //                    image.Save(mStream, System.Drawing.Imaging.ImageFormat.Bmp);
        //                    fileType = ".bmp";
        //                }
        //                else if (image.RawFormat.Guid == System.Drawing.Imaging.ImageFormat.Png.Guid)
        //                {
        //                    image.Save(mStream, System.Drawing.Imaging.ImageFormat.Png);
        //                    fileType = ".png";
        //                }
        //                else if (image.RawFormat.Guid == System.Drawing.Imaging.ImageFormat.Icon.Guid)
        //                {
        //                    image.Save(mStream, System.Drawing.Imaging.ImageFormat.Icon);
        //                    fileType = ".ico";
        //                }
        //                bt = new byte[mStream.Length];
        //                mStream.Position = 0;//设置留的初始位置
        //                mStream.Read(bt, 0, Convert.ToInt32(bt.Length));
        //            }
        //        }
        //    }
        //    return bt;
        //}
        ///// <summary>
        ///// 把Image转换成byte[]
        ///// </summary>
        ///// <param name="_bitmap">图片文件地址(本机)</param>
        ///// <param name="fileType">图片类型</param>
        ///// <returns>获取到的byte[]</returns>
        //public static byte[] GetBytesFromImage(Bitmap _bitmap, out string fileType)
        //{
        //    byte[] bt = null;
        //    fileType = string.Empty;
        //    if (_bitmap == null)
        //        return bt;
        //    Image image = (Image)_bitmap;
        //    using (MemoryStream mStream = new MemoryStream())
        //    {
        //        if (image.RawFormat.Guid == System.Drawing.Imaging.ImageFormat.Tiff.Guid)
        //        {
        //            image.Save(mStream, System.Drawing.Imaging.ImageFormat.Tiff);
        //            fileType = ".tiff";
        //        }
        //        else if (image.RawFormat.Guid == System.Drawing.Imaging.ImageFormat.Gif.Guid)
        //        {
        //            image.Save(mStream, System.Drawing.Imaging.ImageFormat.Gif);
        //            fileType = ".gif";
        //        }
        //        else if (image.RawFormat.Guid == System.Drawing.Imaging.ImageFormat.Jpeg.Guid)
        //        {
        //            image.Save(mStream, System.Drawing.Imaging.ImageFormat.Jpeg);
        //            fileType = ".jpg";
        //        }
        //        else if (image.RawFormat.Guid == System.Drawing.Imaging.ImageFormat.Bmp.Guid)
        //        {
        //            image.Save(mStream, System.Drawing.Imaging.ImageFormat.Bmp);
        //            fileType = ".bmp";
        //        }
        //        else if (image.RawFormat.Guid == System.Drawing.Imaging.ImageFormat.Png.Guid)
        //        {
        //            image.Save(mStream, System.Drawing.Imaging.ImageFormat.Png);
        //            fileType = ".png";
        //        }
        //        else if (image.RawFormat.Guid == System.Drawing.Imaging.ImageFormat.Icon.Guid)
        //        {
        //            image.Save(mStream, System.Drawing.Imaging.ImageFormat.Icon);
        //            fileType = ".ico";
        //        }
        //        bt = new byte[mStream.Length];
        //        mStream.Position = 0;//设置留的初始位置
        //        mStream.Read(bt, 0, Convert.ToInt32(bt.Length));
        //    }
        //    return bt;
        //}

        ///// <summary>
        ///// 把byte[]转换成Image
        ///// </summary>
        ///// <param name="bytes">byte[]</param>
        ///// <returns>获取到的Image</returns>
        //public static Image GetImageFromBytes(byte[] bytes)
        //{
        //    Image photo = null;
        //    using (MemoryStream mStream = new MemoryStream(bytes))
        //    {
        //        mStream.Write(bytes, 0, bytes.Length);
        //        photo = Image.FromStream(mStream, true);
        //    }
        //    return photo;
        //}
        ///// <summary>
        ///// 根据规则组装模型的字符串
        ///// </summary>
        ///// <param name="model"></param>
        ///// <param name="strRule"></param>
        ///// <returns></returns>
        //public static string GetModelInRuleString(object model, string strRule)
        //{
        //    string strRe = string.Empty;
        //    string[] strAry = strRule.Split('|');
        //    string[] strFields = strAry[1].Split(',');
        //    switch (strFields.Length)
        //    {
        //        case 1:
        //            strRe = string.Format(strAry[0], ReflectionHelper.GetPropertyValue(model, strFields[0]));
        //            break;
        //        case 2:
        //            strRe = string.Format(strAry[0], ReflectionHelper.GetPropertyValue(model, strFields[0]), ReflectionHelper.GetPropertyValue(model, strFields[1]));
        //            break;
        //        case 3:
        //            strRe = string.Format(strAry[0], ReflectionHelper.GetPropertyValue(model, strFields[0]), ReflectionHelper.GetPropertyValue(model, strFields[1]), ReflectionHelper.GetPropertyValue(model, strFields[2]));
        //            break;
        //    }
        //    return strRe;
        //}
        /// <summary>
        /// 通过序列化的方式，深拷贝一个对象
        /// </summary>
        /// <typeparam name="T">对象的类型</typeparam>
        /// <param name="t">对象</param>
        /// <returns></returns>
        public static T Copy<T>(T t)
        {
            var json = Newtonsoft.Json.JsonConvert.SerializeObject(t);
            T copy = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(json);
            return copy;
        }

        /// <summary>
        /// DataTable转换成泛型列表 2019.5.23 added by yz
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static List<T> ToList<T>(this DataTable dt)
        {
            var lst = new List<T>();
            var plist = new List<System.Reflection.PropertyInfo>(typeof(T).GetProperties());
            foreach (DataRow item in dt.Rows)
            {
                T t = System.Activator.CreateInstance<T>();
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    PropertyInfo info = plist.Find(p => p.Name == dt.Columns[i].ColumnName);
                    if (info != null)
                    {
                        if (!Convert.IsDBNull(item[i]))
                        {
                            info.SetValue(t, item[i], null);
                        }
                    }
                }
                lst.Add(t);
            }
            return lst;
        }
    }
}
